package com.hu.handler;

import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.Head;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.write.handler.CellWriteHandler;
import com.alibaba.excel.write.handler.context.CellWriteHandlerContext;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.metadata.holder.WriteTableHolder;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import org.apache.poi.ss.usermodel.*;

import java.util.Map;

/**
 * 标题处理器
 * @author author
 * @date 2024-07-31 9:16
 */
public class ExcelHeaderHandler implements CellWriteHandler {

    private Map<String, String> headerColorMap;

    public ExcelHeaderHandler(Map<String, String> headerColorMap) {
        this.headerColorMap = headerColorMap;
    }

    @Override
    public void afterCellDispose(CellWriteHandlerContext context) {
        if (context.getHead()) {
            Workbook workbook = context.getWriteWorkbookHolder().getWorkbook();
            WriteCellData<?> cellData = context.getFirstCellData();
            // 设置背景颜色，也可以设置字体等其它元素
            WriteCellStyle writeCellStyle = cellData.getOrCreateStyle();
            // 设置背景颜色
            writeCellStyle.setFillForegroundColor(IndexedColors.GREY_80_PERCENT.index);
            CellStyle cellStyle = workbook.createCellStyle();
            // 设置边框样式
            cellStyle.setBorderTop(BorderStyle.THIN);
            cellStyle.setBorderBottom(BorderStyle.THIN);
            cellStyle.setBorderLeft(BorderStyle.THIN);
            cellStyle.setBorderRight(BorderStyle.THIN);
            Font font = workbook.createFont();
            // 字体加粗
            font.setBold(true);
            cellStyle.setFont(font);
            Cell cell = context.getCell();
            cell.setCellStyle(cellStyle);
            // 根据传来的字符串判断颜色
            String color = headerColorMap.get(context.getHeadData().getHeadNameList().get(0));
            if (color != null && "red".equals(color)) {
                font.setColor(Font.COLOR_RED);
            }
            // 由于这里没有指定dataformat 最后展示的数据 格式可能会不太正确
            // 这里要把 WriteCellData的样式清空， 不然后面还有一个拦截器 FillStyleCellWriteHandler 默认会将 WriteCellStyle 设置到
            // cell里面去 会导致自己设置的不一样
            context.getFirstCellData().setWriteCellStyle(null);
            writeCellStyle.setFillPatternType(FillPatternType.SOLID_FOREGROUND);
        } else {
            Workbook workbook = context.getWriteWorkbookHolder().getWorkbook();
            CellStyle cellStyle = workbook.createCellStyle();
            cellStyle.setWrapText(true);
            Cell cell = context.getCell();
            cell.setCellStyle(cellStyle);
        }
    }

}
